package com.zrf.gulimall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.zrf.gulimall.commnon.core.es.SkuEsModel;
import com.zrf.gulimall.search.conf.ElasticConfig;
import com.zrf.gulimall.search.contanst.ElasticConstant;
import com.zrf.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zhanrf
 * @Date 2021/12/19 1:30
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
	@Resource
	private RestHighLevelClient esClient;

	@Override
	public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
		BulkRequest bulkRequest = new BulkRequest();
		for (SkuEsModel skuEsModel : skuEsModels) {
			IndexRequest indexRequest = new IndexRequest(ElasticConstant.PRODUCT_INDEX);
			String jsonStr = JSONUtil.toJsonStr(skuEsModel);
			indexRequest.id(skuEsModel.getSkuId().toString());
			indexRequest.source(jsonStr, XContentType.JSON);
			bulkRequest.add(indexRequest);
		}
		BulkResponse bulkResponse = esClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
		if (bulkResponse.hasFailures()) {
			List<String> failIds = Arrays.stream(bulkResponse.getItems()).filter(BulkItemResponse::isFailed).map(BulkItemResponse::getId).collect(Collectors.toList());
			log.error("索引失败，分别为{}", failIds);
		}
		// 返回批量操作是否有失败
		return !bulkResponse.hasFailures();
	}
}
